package com.cmic.rcs.emoji.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * CommonUtils
 *
 * @author hzr
 * @since 1.0.0
 */
@Slf4j
@Component
public class FileUtils {

    @Value("${spring.profiles.active}")
    private String active;

    @Value("${file-gateway.upload.url:http://origin-file-gateway.ecpan-asp:8080/origin-file-gateway/inner/file/upload}")
    private String uploadUrl;
    @Value("${file-gateway.upload.orgId:}")
    private String uploadOrgId;

    @Autowired
    private OkHttpClient okHttpClient;
    @Autowired
    private ObjectMapper objectMapper;

    public String storeImg(MultipartFile file, String md5, String ext) throws IOException {
        String filename = md5 + "." + ext;
        byte[] fileBytes = file.getBytes();
        RequestBody fileBody = RequestBody.create(fileBytes);
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("name", filename)
                .addFormDataPart("size", String.valueOf(file.getSize()))
                .addFormDataPart("hashValue", DigestUtils.sha256Hex(fileBytes))
                .addFormDataPart("directory", "custom-emoji")
                .addFormDataPart("orgId", uploadOrgId)
                .addFormDataPart("type", "single")
                .addFormDataPart("file", filename, fileBody)
                .build();

        Request request = new Request.Builder()
                .url(uploadUrl)
                .post(requestBody)
                .build();
        Call call = okHttpClient.newCall(request);
        try (Response response = call.execute()) {
            if (!response.isSuccessful() || response.body() == null) {
                log.info("file upload request null");
                return null;
            }
            FileUploadRespDto respDto = objectMapper.readValue(response.body().bytes(), FileUploadRespDto.class);
            log.info("file upload resp: {}", respDto);
            if (respDto.isSuccessful()) {
                return respDto.getData();
            }
        } catch (Exception e) {
            log.error("file upload error: {}", e.toString(), e);
        }
        return null;
    }

    public String storeImg(byte[] fileBytes, String md5, String ext) throws IOException {
        if ("local".equals(active)) {
            File file = new File("F:\\WorkProjects\\emoji-server\\表情包2\\" + md5 + "-" + fileBytes.length + "." + ext);
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(fileBytes);
            fos.close();
            return md5 + "-" + fileBytes.length + "." + ext;
        }
        String filename = md5 + "." + ext;
        RequestBody fileBody = RequestBody.create(fileBytes);
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("name", filename)
                .addFormDataPart("size", String.valueOf(fileBytes.length))
                .addFormDataPart("hashValue", DigestUtils.sha256Hex(fileBytes))
                .addFormDataPart("directory", "custom-emoji")
                .addFormDataPart("orgId", uploadOrgId)
                .addFormDataPart("type", "single")
                .addFormDataPart("file", filename, fileBody)
                .build();

        Request request = new Request.Builder()
                .url(uploadUrl)
                .post(requestBody)
                .build();
        Call call = okHttpClient.newCall(request);
        try (Response response = call.execute()) {
            if (!response.isSuccessful() || response.body() == null) {
                log.info("file upload request null");
                return null;
            }
            FileUploadRespDto respDto = objectMapper.readValue(response.body().bytes(), FileUploadRespDto.class);
            log.info("file upload resp: {}", respDto);
            if (respDto.isSuccessful()) {
                return respDto.getData();
            }
        } catch (Exception e) {
            log.error("file upload error: {}", e.toString(), e);
        }
        return null;
    }

    @Data
    public static class FileUploadRespDto {
        private Integer code;
        private String result;
        private String data;

        public boolean isSuccessful() {
            return code != null && code == 0;
        }
    }

    private static final List<String> FILE_IMAGE_EXT = Arrays.asList("WEBP", "BMP", "PCX", "TIF", "GIF", "JPEG", "JPG", "TGA", "EXIF", "FPX", "SVG", "PSD", "CDR", "PCD", "DXF", "UFO", "EPS", "AI", "PNG", "HDRI", "RAW", "WMF", "FLIC", "EMF", "ICO");

    public static boolean isImage(String ext) {
        return ext != null && FILE_IMAGE_EXT.contains(ext.toUpperCase());
    }

}
